
const crypto = require('crypto')

/**
 * @description: 加密
 * @param {password}  采用的密码
 * @return {*}
 */
const key1 = crypto.scryptSync('password', 'salt', 64);
// toString参数：hex, utf8, ascii, binary, base64, ucs2
console.log(key1, key1.length, key1.toString('base64'));
// dFcxr0SE8yOWiWntoomu7gBbWQOsVh5kpayhIXl793NO+f1YQi4uIhg7ysup7Ie6DIO3oueI8Dzg2gZGNDPNpg==  base64
// 745731af4484f323968969eda289aeee005b5903ac561e64a5aca121797bf7734ef9fd58422e2e22183bcacba9ec87ba0c83b7a2e788f03ce0da06463433cda6  hex

/**
 * @description: 
 * @param {*}
 * @return {*}
 */
const encrypt = (password, string) => {
    // 对称加密算法类型
    const algorithm = 'aes-192-cbc';
    // 生成对称加密密钥，defineSalt定义一个生成密钥的盐，指定密钥长度24，scrypt是一个基于密码的密钥派生函数
    const key = crypto.scryptSync(password, 'defineSalt1', 24)
    console.log('key',key)
    console.log(`key-length:${key.length}, key-value:${key.toString("hex")}`);

    // 初始化向量，Buffer.from和Buffer.alloc都是生成buffer，Buffer.from从字符串或数组创建buffer，Buffer.alloc创建指定大小的buffer
    const iv = Buffer.alloc(16, 0)
    // 获得Cipher的加密类
    const cipher = crypto.createCipheriv(algorithm, key, iv)

    let encryptedString = cipher.update(string, 'utf-8', 'hex')
    encryptedString += cipher.final('hex')
    return encryptedString;
}

const password = "shenshuai"
// 需要被加密的数据
const encryptedString = encrypt(password, "node的crypto实现对称加密")
console.log(`加密后的数据：${encryptedString}`);

/**
 * @description: 解密
 * @param {*}
 * @return {*}
 */
const decrypt = (password, encryptedString) => {
    const algorithm = 'aes-192-cbc'
    // 采用相同的算法和salt值，计算出相同的密钥
    const key = crypto.scryptSync(password, 'defineSalt1', 24)
    const iv = Buffer.alloc(16, 0)
    console.log(`解密是的密钥key：${key.toString("hex")}`)
    // 解密方法createDecipheriv
    const decipher = crypto.createDecipheriv(algorithm, key, iv)
    let decryptedString = decipher.update(encryptedString, 'hex', 'utf-8')
    decryptedString += decipher.final('utf8')
    return decryptedString;
}
const decryptedString = decrypt(password, encryptedString);
console.log(`解密后的数据：${decryptedString}`)